package com.example.yichuangyun.mvvm.ui.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityMapSearchBinding;
import com.example.yichuangyun.dialog.ContactsCompanyDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.company.CompanyDataModel;
import com.example.yichuangyun.model.company.CompanyDetailsContactsDataModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.adapter.SearchCompanyAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.view.SearchCompanyViewModel;
import com.example.yichuangyun.mvvm.ui.map.ClusterClickListener;
import com.example.yichuangyun.mvvm.ui.map.ClusterOverlay;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DensityUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.widget.MyBottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 附近企业 地图
 */
public class MapSearchActivity extends BaseActivity<ActivityMapSearchBinding, SearchCompanyViewModel> implements AMap.OnMapLoadedListener, ClusterClickListener {

    private ActivityResultLauncher<Intent> searchLauncher;
    private LinearLayout llSearch;
    private TextView tvCompanyCount;
    private MyBottomSheetBehavior<View> behavior;
    private SearchCompanyAdapter adapter;
    private RecyclerView recyclerView;
    private MapView mapView;
    private AMap mAMap;
    private MyLocationStyle myLocationStyle;
    private final int clusterRadius = 50;
    private ClusterOverlay mClusterOverlay;

    private Double latitude, longitude;
    private boolean isNeedLocation = true;
    private CompanyDataModel.CompanyModel mCompanyModel;
    private CompanyDataModel.CompanyModel mModel;
    private int mPosition;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_search);
        CommonUtil.requestTranslucentStatusBar(this, true);
        View bottomSheet = findViewById(R.id.bottom_sheet);
        behavior = MyBottomSheetBehavior.from(bottomSheet);
        llSearch = findViewById(R.id.ll_search);
        tvCompanyCount = findViewById(R.id.tv_company_count);
        ImageView ivBack = findViewById(R.id.iv_back);
        ImageView ivList = findViewById(R.id.iv_list);
        ivBack.setOnClickListener(view -> finish());
        ivList.setOnClickListener(view -> finish());
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        adapter = new SearchCompanyAdapter(this);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setAdapter(adapter);
        initMyData();
        init();
        initListener();
    }

    private void initMyData() {
        searchLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    Constant.isSearch = true;
                    isNeedLocation = true;
                    mModel = (CompanyDataModel.CompanyModel) result.getData().getExtras().get(Constant.modelKey);
                    if (mModel != null) {
                        latitude = mModel.getLatitude();
                        longitude = mModel.getLongitude();
                    }
                    getCompanyList();
                }
            }
        });
    }

    @Override
    protected SearchCompanyViewModel bindModel() {
        return getViewModel(this, SearchCompanyViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
    }

    private void getCompanyList() {
        Map<String, Object> map = new HashMap<>();
        if (isNeedLocation) {
            map.put("isAppMap", 1);
        }
        map.put("pageSize", 100);
        map.put("distance", 0.3);
        // 点击搜索条目后经纬度取值为列表的latitude和latitude
        if (Constant.isSearch) {
            map.put("latitude", latitude);
            map.put("longitude", longitude);
        } else {
            // 首次进入key传gd取值为高德地图api返回的经纬度
            map.put("gdLatitude", latitude);
            map.put("gdLongitude", longitude);
        }
        viewModel.getCompanyList(map);
    }

    private void init() {
        if (mAMap == null) {
            // 初始化地图
            mAMap = mapView.getMap();
            mAMap.setOnMapLoadedListener(this);
            // 定位蓝点
            myLocationStyle = new MyLocationStyle();
            myLocationStyle.showMyLocation(true);
            myLocationStyle.radiusFillColor(Color.TRANSPARENT);
            myLocationStyle.strokeWidth(0);
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_location_now)));
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
            mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
            mAMap.getUiSettings().setMyLocationButtonEnabled(true); //设置默认定位按钮是否显示，非必需设置。
            mAMap.setMyLocationEnabled(true); // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
            mAMap.setOnMyLocationChangeListener(location -> {
                if (isNeedLocation) {
                    Constant.isSearch = false;
                    isNeedLocation = false;
                    Log.e("@@@@@@@@---mapSearch", "纬度：" + location.getLatitude() + "，经度：" + location.getLongitude());
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    if (latitude == 0 && longitude == 0) {
                        ToastHelper.showLong("请检查是否开启定位权限");
                    }
                    getCompanyList();
                }
            });
        }
    }

    protected void initListener() {
        // 企业列表返回结果
        viewModel.companyDataModelMutableLiveData.observe(this, companyDataModel -> {
            if (null != companyDataModel.getData()) {
                adapter.setLocation(latitude, longitude);
                List<CompanyDataModel.CompanyModel> data = companyDataModel.getData();
                if (data != null && !data.isEmpty()) {
                    if (mModel != null) {
                        int index = -1;
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getEid().equals(mModel.getEid())) {
                                index = i;
                                break;
                            }
                        }
                        // 如果目标企业不在搜索列表中，则加入到list中并放第一个位置上
                        // 如果目标企业在列表中，但不在第一个位置上，则交换位置（换到第一个位置上）
                        if (index == -1) {
                            data.add(0, mModel);
                        } else {
                            if (!mModel.getEid().equals(data.get(0).getEid())) {
                                Collections.swap(data, index, 0);
                            }
                        }
                    }

                    mAMap.clear();
                    if (!isNeedLocation) {
                        mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
                    }
                    LatLng latLng = new LatLng(latitude, longitude);
                    mAMap.addCircle(new CircleOptions().center(latLng).radius(1000).fillColor(0x240F8AE9).strokeColor(0x4D81ABCE).strokeWidth(4));
                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));//设置地图放大为14倍
                    mClusterOverlay = new ClusterOverlay(mAMap, data.size() > 100 ? data.subList(0, 100) : data, DensityUtil.dip2px(context, clusterRadius), getApplicationContext());
                    mClusterOverlay.setOnClusterClickListener(MapSearchActivity.this);
                }
            }
        });

        // 收藏
        adapter.addOnItemChildClickListener(R.id.ll_like, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            // 0未收藏、1已收藏
            if (null != mCompanyModel) {
                if (mCompanyModel.getCollectState() == 0) {
                    viewModel.collectCompany(mCompanyModel);
                } else {
                    viewModel.cancelCollectCompany(mCompanyModel.getEid());
                }
            }
        });

        // 收藏成功返回结果
        viewModel.collectSuccessMutableLiveData.observe(this, s -> {
            mCompanyModel.setCollectState(1);
            adapter.notifyItemChanged(mPosition, "1");
            ToastHelper.show(getString(R.string.collect_success));
        });

        // 取消收藏返回结果
        viewModel.cancelCollectSuccessMutableLiveData.observe(this, s -> {
            mCompanyModel.setCollectState(0);
            adapter.notifyItemChanged(mPosition, "1");
            ToastHelper.show(getString(R.string.cancel_collect_success));
        });

        adapter.addOnItemChildClickListener(R.id.ll_call, (baseQuickAdapter, view, i) -> {
            CompanyDataModel.CompanyModel item = baseQuickAdapter.getItem(i);
            if (null != item) {
                viewModel.getContacts(item.getEid());
            }
        });

        // 可拨打电话返回结果
        viewModel.contactsMutableLiveData.observe(this, contactsModels -> {
            if (null != contactsModels && !contactsModels.isEmpty()) {
                initDialog(contactsModels);
            } else {
                ToastHelper.show(getString(R.string.no_contact_phone));
            }
        });

        llSearch.setOnClickListener(view -> {
            Intent intent = new Intent(MapSearchActivity.this, SearchCompanyActivity.class);
            intent.putExtra(Constant.flagKey, 1);
            searchLauncher.launch(intent);
            if (behavior.getState() != MyBottomSheetBehavior.STATE_COLLAPSED) {
                behavior.setState(MyBottomSheetBehavior.STATE_COLLAPSED);
                adapter.submitList(null);
            }
        });

        adapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(this, CompanyDetailsActivity.class, bundle);
        });

        adapter.addOnItemChildClickListener(R.id.tv_reg_address, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(this, CompanyDetailsActivity.class, bundle);
        });

        adapter.addOnItemChildClickListener(R.id.tv_report_address, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(this, CompanyDetailsActivity.class, bundle);
        });
    }

    private void initDialog(List<CompanyDetailsContactsDataModel.ContactsModel> contactsData) {
        ContactsCompanyDialog contactsCompanyDialog = new ContactsCompanyDialog(context, contactsData, 4);
        contactsCompanyDialog.showDialog();
    }

    @Override
    public void onMapLoaded() {

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    protected void onDestroy() {
        super.onDestroy();
        Constant.isSearch = false;
        // 销毁资源
        if (mClusterOverlay != null) {
            mClusterOverlay.onDestroy();
        }
        mapView.onDestroy();
    }

    @Override
    public void onClick(Marker marker, List<CompanyDataModel.CompanyModel> clusterItems) {
        // 点击会继续放大地图
//        LatLngBounds.Builder builder = new LatLngBounds.Builder();
//        for (RegionItem clusterItem : clusterItems) {
//            builder.include(clusterItem.getPosition());
//        }
//        LatLngBounds latLngBounds = builder.build();
//        mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 0));

        if (behavior.getState() != MyBottomSheetBehavior.STATE_HALF_EXPANDED) {
            behavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED);
        }
        tvCompanyCount.setText(Html.fromHtml(getString(R.string.find_nearby_company_count, clusterItems.size()), Html.FROM_HTML_MODE_LEGACY));
        adapter.submitList(clusterItems);
        recyclerView.scrollToPosition(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshCompanyList)) {
                mCompanyModel.setCollectState(eventBusModel.getStatus());
                adapter.notifyItemChanged(mPosition, "1");
            }
        }
    }
}